package tjs.study.notes.dotest.disruptor.apiLog.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;
import tjs.study.notes.dotest.disruptor.apiLog.bean.ApiLogModelWriteDto;
import tjs.study.notes.dotest.disruptor.apiLog.config.DisruptorProducer;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * WriteLogService
 * Created by Nicky.Tang on 2022/9/29 下午2:10
 *
 * @since 02.12.10
 */
public class WriteLogService {
    @Autowired
    private DisruptorProducer disruptorProducer;

    public void sendWriteLog(String accessKey, Object errMsg, Long startTime, ContentCachingRequestWrapper request, ContentCachingResponseWrapper response) {
        Long curTs = System.currentTimeMillis();
        ApiLogModelWriteDto apiLogModel = new ApiLogModelWriteDto();
        apiLogModel.setAccessKey(accessKey);
        apiLogModel.setStartTime(startTime);
        apiLogModel.setSpendTime(curTs - startTime);
        apiLogModel.setUrl(request.getRequestURL().toString());

        apiLogModel.setRequestJson(JSONObject.toJSONString(getRequestBody(request), true));
        apiLogModel.setResponseJson(JSONObject.toJSONString(getResponseBody(response), true));
        // 先放入 disruptor队列中
        disruptorProducer.sendJson(apiLogModel);

    }

    public void doWriteLog(List<ApiLogModelWriteDto> datas) {
        Long curTs = System.currentTimeMillis();
        datas.stream().forEach(item -> item.setCreateTime(curTs));
        // 再存入数据库
        System.out.println(JSONObject.toJSONString(datas));
    }

    private String getRequestBody(ContentCachingRequestWrapper response) {
        ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(response, ContentCachingRequestWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                String payload;
                try {
                    payload = new String(buf, 0, buf.length, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    payload = "[unknown]";
                }
                return payload;
            }
        }
        return "";
    }

    private String getResponseBody(ContentCachingResponseWrapper response) {
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                String payload;
                try {
                    payload = new String(buf, 0, buf.length, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    payload = "[unknown]";
                }
                return payload;
            }
        }
        return "";
    }
}
